//Documentation complete
/**
 * @author Alex
 * @version 2009MR16
 */

package ui.internal;

import control.*;
import problemDomain.*;
import problemDomain.ErrorBean.ErrorCode;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.*;

import org.jCharts.axisChart.ScatterPlotAxisChart;
import org.jCharts.encoders.PNGEncoder;

/**
 * Servlet implementation class ReportProfitabilityPopularity
 */
public class ReportProfitabilityPopularity extends HttpServlet {
	
	/* Constants */
	
	private static final long serialVersionUID = 8360406193246230221L;
	
	private static DateFormat DATE_FORMAT = new SimpleDateFormat("dd-MMM-yyyy");
	
	/* END Constants */
	
	
	/* (HttpServlet) Methods */
	
	@Override
	protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String fromStr = request.getParameter("dateFrom");
		String toStr = request.getParameter("dateTo");
		
		if (fromStr != null && toStr != null) {
			PrintWriter out = response.getWriter();
			try {
				try {
					Date from = DATE_FORMAT.parse(fromStr);
					Date to = DATE_FORMAT.parse(toStr);
				
					ProductivityPopularityReportControl pprc = new ProductivityPopularityReportControl();
					ScatterPlotAxisChart chart = pprc.report(from, to);
					
					response.setContentType("image/png");
					PNGEncoder.encode(chart, response.getOutputStream());
					
				} catch (Exception e) {
					throw new ErrorBean(ErrorCode.REPORT_CANNOT_GENERATE_REPORT, e.getMessage());
				}
			} catch (ErrorBean e) {
				out.write(e.toXML());
			}
		}
	}
	
	/* END (HttpServlet) Methods */
	
}
